package per.dj.testpro.service.impl;

import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import per.dj.testpro.entity.GpsConnection;
import per.dj.testpro.mapper.SendMessageMapper;
import per.dj.testpro.model.RechargeStationInfo;
import per.dj.testpro.model.SendMessage;
import per.dj.testpro.service.TimeTaskService;
import per.dj.testpro.utils.common.Tools;

import java.util.Date;
import java.util.List;

@Component
@Configurable
@EnableScheduling
public class TimeTaskServiceImpl extends BaseServiceImpl implements TimeTaskService {

    @Override
    @Scheduled(fixedRate = 1000 * 5)
    public void sendMsgToLowerMachine() {
        Date now = new Date();
        Date beforeDate = new Date(now.getTime() - 300000);
        List<SendMessage> sendMessageList = sendMessageMapper.selectByTimeTask(0,beforeDate);

        SendMessage sendMessage = null;
        String imeiNo = "";
        String strSendMessage = "";
        for(int i=0;i<sendMessageList.size();i++){
            sendMessage = sendMessageList.get(i);
            imeiNo = sendMessage.getImeiNo();
            sendMessage.setIsSuccess(3);
            sendMessageMapper.updateByPrimaryKeySelective(sendMessage);
            strSendMessage=sendMessage.getMessage();
            byte[] byteSendMsg = Tools.HexString2Bytes(strSendMessage);
            serverHandler.send(imeiNo, byteSendMsg);
        }
    }

    @Override
    //@Scheduled(cron = "0 */8 *  * * * ")
    public void checkLastConnection() {

        List<RechargeStationInfo> rechargeStationInfoList = rechargeStationInfoMapper.getRechargeStationInfoList(1);
        RechargeStationInfo rechargeStationInfo = null;
        long diffMinutes=0;
        Date dt = new Date();
        String imeiNo = "";
        for(int i=0;i<rechargeStationInfoList.size();i++){
            rechargeStationInfo = rechargeStationInfoList.get(i);
            diffMinutes = (dt.getTime() - rechargeStationInfo.getLastConnectTime().getTime())/1000/60;
            if(diffMinutes>=8){
                imeiNo = rechargeStationInfo.getImeiNo();
                rechargeStationInfo.setIsonline(0);
                rechargeStationInfoMapper.updateByPrimaryKeySelective(rechargeStationInfo);
                try {
                    GpsConnection conn = serverHandler.getConnctionMap().get(imeiNo);
                    if (conn != null) {
                        ChannelHandlerContext ctx = conn.getNettyChannel();
                        serverHandler.channelInactive(ctx);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
